package top.yongyan0624.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import top.yongyan0624.common.lang.Result;
import top.yongyan0624.entity.ItemBorrowUser;
import top.yongyan0624.entity.PropertyPay;
import top.yongyan0624.entity.PropertyPayProject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yongyan
 * @since 2021-09-15
 */
@RestController
@RequestMapping("/property/pay")
public class PropertyPayController extends BaseController {

    @GetMapping("/show/{id}")
    public Result show(String name, @PathVariable("id") Long userId) {
        Page<PropertyPay> pageData = propertyPayService.page(getPage(), new QueryWrapper<PropertyPay>()
                .eq("user_id", userId).orderByDesc("create_time"));

        //用以存储不符合title模糊查询的item
        List<PropertyPay> delItem = new ArrayList<>();

        pageData.getRecords().forEach(pay -> {
            pay.setProject(propertyPayProjectService.getById(pay.getProjectId()).getName());
            if (name != null && !pay.getProject().contains(name)){
                delItem.add(pay);
            }
            pay.setUser(sysUserService.getById(pay.getUserId()));
        });

        pageData.getRecords().removeAll(delItem);

        return Result.success(pageData);
    }

    @PostMapping("/save")
    public Result save(@RequestBody PropertyPay pay){
        propertyPayService.save(pay);

        pay.setProject(propertyPayProjectService.getById(pay.getProjectId()).getName());
        pay.setUser(sysUserService.getById(pay.getUserId()));

        return Result.success(pay);
    }

    @PostMapping("/update")
    @PreAuthorize("hasAuthority('pay:update')")
    public Result update(@RequestBody PropertyPay pay){
        propertyPayService.updateById(pay);

        pay.setProject(propertyPayProjectService.getById(pay.getProjectId()).getName());
        pay.setUser(sysUserService.getById(pay.getUserId()));

        return Result.success(pay);
    }

    @Transactional
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('pay:delete')")
    public Result delete(@RequestBody Long[] ids) {
        propertyPayService.removeByIds(Arrays.asList(ids));

        return Result.success("");
    }
}
